﻿using System;
using UnityEngine;
#if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
using UnityEngine.InputSystem;
#endif

namespace Assets.Common.Unity
{
    public class MouseUIFollow : MonoBehaviour
    {
        [SerializeField] private Canvas _canvas;

        public Canvas TargetCanvas
        {
            get => _canvas;
            set => _canvas = value;
        }

        protected Vector2 _newPosition;
        protected Vector2 _mousePosition;

        private void Awake()
        {
            _canvas = GetComponentInParent<Canvas>();
        }

        protected virtual void LateUpdate()
        {
#if !ENABLE_INPUT_SYSTEM || ENABLE_LEGACY_INPUT_MANAGER
			_mousePosition = Input.mousePosition;
#else
            _mousePosition = Mouse.current.position.ReadValue();
#endif
            RectTransformUtility.ScreenPointToLocalPointInRectangle(TargetCanvas.transform as RectTransform,
                _mousePosition, TargetCanvas.worldCamera, out _newPosition);
            //控制锚点，防止位置在屏幕外
            var xOffset = _mousePosition.x / Screen.width - 0.5f;
            //右边时锚点x =1 ,左边0
            var pivot = (transform as RectTransform).pivot;
            pivot.x = xOffset > 0 ? 1f : 0f;
            (transform as RectTransform).pivot = pivot;
            transform.position = TargetCanvas.transform.TransformPoint(_newPosition);
        }
    }
}